<template>
    <div class="white-box-form">
        <el-form
            ref="ruleRef"
            :model="state.ruleForm"
            :rules="state.rules"
            label-width="140px"
            class="mt-20"
        >
            <el-form-item label="优惠券名称" prop="couponName">
                <el-input
                    v-model.trim="state.ruleForm.couponName"
                    clearable
                    placeholder="请输入优惠券名称"
                />
            </el-form-item>
            <el-form-item label="优惠券类型" prop="couponType">
                <el-radio-group v-model="state.ruleForm.couponType">
                    <el-radio
                        v-for="item in state.couponTypeList"
                        :key="item.memberKey"
                        :value="item.memberKey"
                        >{{ item.memberName }}</el-radio
                    >
                </el-radio-group>
            </el-form-item>
            <el-form-item label="最低使用额度(元)" prop="minAmount">
                <el-input-number
                    v-model="state.ruleForm.minAmount"
                    :min="0"
                    :precision="2"
                />
            </el-form-item>
            <el-form-item label="优惠额度(元)" prop="preferential">
                <el-input-number
                    v-model="state.ruleForm.preferential"
                    :min="0"
                    :precision="2"
                />
            </el-form-item>
            <el-form-item
                v-if="state.ruleForm.couponType === 2"
                label="优惠比例(折)"
                prop="ratio"
            >
                <el-input-number
                    v-model="state.ruleForm.ratio"
                    :min="0"
                    :max="10"
                    :precision="2"
                />
            </el-form-item>
            <el-form-item label="是否限制领取数量" prop="limitation">
                <el-radio-group v-model="state.ruleForm.limitation">
                    <el-radio :value="0">是</el-radio>
                    <el-radio :value="1">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item
                v-if="state.ruleForm.limitation === 0"
                label="每人可领取数量"
                prop="number"
            >
                <el-input-number
                    v-model="state.ruleForm.number"
                    :min="1"
                    :precision="0"
                />
            </el-form-item>
            <el-form-item label="优惠券过期时间" prop="expireTime">
                <el-date-picker
                    v-model="state.ruleForm.expireTime"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    time-format="HH:mm"
                    :disabled-date="disabledDate"
                    :disabled-hours="disabledHours"
                    :disabled-minutes="disabledMinutes"
                    :default-time="new Date(Date.now() + 60000)"
                    placeholder="请选择优惠券过期时间"
                />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="state.ruleForm.status">
                    <el-radio
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :value="item.memberKey"
                        >{{ item.memberName }}</el-radio
                    >
                </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="note">
                <el-input
                    v-model.trim="state.ruleForm.note"
                    type="textarea"
                    maxlength="100"
                    :autosize="{ minRows: 2 }"
                    clearable
                    show-word-limit
                    placeholder="请输入备注"
                />
            </el-form-item>
        </el-form>

        <div class="foot-btn">
            <el-button
                type="primary"
                :loading="state.form_loading"
                @click="submitForm(ruleRef)"
            >
                {{ isEdit ? "修改" : "添加" }}
            </el-button>
        </div>
        <go-back />
    </div>
</template>

<script setup>
import { inject, ref, onMounted, reactive, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import GoBack from "@components/GoBack.vue";
import {
    getCouponDetail,
    addCoupon,
    editCoupon,
} from "@/apis/marketing/coupon.js";
import { fenToYuan, yuanToFen, formatDate } from "@/assets/common/utils.js";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));
dictStore
    .getDictMembers("coupon_type")
    .then((res) => (state.couponTypeList = res));

const router = useRouter();
const route = useRoute();

const $message = inject("$message");

const sid = route.query.sid;
const isEdit = ref(false);
const form_loading = ref(false);
const ruleRef = ref(null);
const state = reactive({
    statusList: [],
    couponTypeList: [],
    ruleForm: {
        couponName: null,
        couponType: 1,
        expireTime: null,
        note: null,
        minAmount: 0,
        ratio: null,
        preferential: 0,
        status: 0,
        limitation: 1,
        number: 1,
    },
    rules: {
        couponName: [
            { required: true, message: "请输入优惠券名称", trigger: "blur" },
        ],
        couponType: [
            { required: true, message: "请选择优惠券类型", trigger: "blur" },
        ],
        minAmount: [
            { required: true, message: "请输入最低使用额度", trigger: "blur" },
        ],
        preferential: [
            { required: true, message: "请输入优惠额度", trigger: "blur" },
        ],
        ratio: [{ required: true, message: "请输入优惠比例", trigger: "blur" }],
        number: [
            {
                required: true,
                message: "请输入每人可领取数量",
                trigger: "blur",
            },
        ],
        limitation: [
            {
                required: true,
                message: "请选择是否限制领取数量",
                trigger: "blur",
            },
        ],
    },
});

onMounted(() => {
    if (/Edit$/.test(route.name)) {
        isEdit.value = true;
        getDetail();
    }
});

const getDetail = async () => {
    const res = await getCouponDetail({ sid });
    if (res.data.code == 200) {
        const { minAmount, preferential, ratio, couponType } = res.data.data;
        state.ruleForm = res.data.data;
        state.ruleForm.minAmount = Number(fenToYuan(minAmount));
        state.ruleForm.preferential = Number(fenToYuan(preferential));
        if (couponType === 2) {
            // 比例优惠券
            state.ruleForm.ratio = Number(ratio) * 10;
        }
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const disabledDate = (time) => {
    return time.getTime() <= Date.now() - 1000 * 3600 * 24;
};

const makeRange = (start, end) => {
    const result = [];
    for (let i = start; i <= end; i++) {
        result.push(i);
    }
    return result;
};

// 是否选择今天
const isSelectedToday = computed(() => {
    const { expireTime } = state.ruleForm;
    if (!expireTime) return false;

    const expireDate = new Date(expireTime);
    const year = expireDate.getFullYear();
    const month = expireDate.getMonth();
    const day = expireDate.getDay();

    const date = new Date();
    const nowYear = date.getFullYear();
    const nowMonth = date.getMonth();
    const nowDay = date.getDay();
    if (year === nowYear && month === nowMonth && day === nowDay) {
        return true;
    } else {
        return false;
    }
});

const disabledHours = () => {
    // 同一天则禁用掉当前时间之前的所有时间
    if (isSelectedToday.value) {
        return makeRange(0, new Date().getHours() - 1);
    }
};

const disabledMinutes = () => {
    // 同一天则禁用掉当前时间之前的所有时间
    if (isSelectedToday.value) {
        return makeRange(0, new Date().getMinutes());
    }
};

// 提交表单
const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            form_loading.value = true;
            let res = null;
            const form = {
                ...state.ruleForm,
                minAmount: yuanToFen(state.ruleForm.minAmount),
                preferential: yuanToFen(state.ruleForm.preferential),
            };
            if (form.couponType === 2) {
                // 比例优惠券
                form.ratio = form.ratio / 10;
            }
            if (form.expireTime) {
                form.expireTime = formatDate(
                    new Date(form.expireTime).setSeconds(0)
                );
            }
            if (form.limitation === 1) {
                form.number = null;
            }
            if (isEdit.value) {
                res = await editCoupon(form);
            } else {
                res = await addCoupon(form);
            }
            form_loading.value = false;
            if (res.data.code == 200) {
                $message({
                    message: isEdit.value ? "修改成功" : "添加成功",
                    type: "success",
                });
                router.back();
            } else {
                $message({ message: res.data.msg, type: "error" });
            }
        }
    });
};
</script>
